#!/bin/bash

. config.sh # 引入config.sh脚本

# 获取当前目录
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# 获取父目录
Basefolder="$(cd ../; pwd)" 

# 为方便停止/启动/重启创建systemctl
Systemd=$DIR/"systemd"
main="$MAINPID"
if [ ! -d "$Systemd" ] 
then
 mkdir systemd # 如果不存在systemd目录，则创建它
fi
# 生成 UAVcast.service 文件
FILE=$DIR/"systemd/UAVcast.service"

/bin/cat <<EOM >$FILE
# 以下为 UAVcast.service 文件的内容
[Unit]
Description=UAVcast Drone Software # 描述：UAVcast 无人机软件
Requires=network-online.target
Wants=network-online.target
After=network-online.target
[Service]
WorkingDirectory=/home/pi/UAVcast # 工作目录
Type=forking
GuessMainPID=no
ExecStart=/bin/bash DroneStart.sh start # 启动时执行的命令
KillMode=control-group
Restart=on-failure # 失败时重启
[Install]
WantedBy=network-online.target
EOM

# 将生成的 UAVcast.service 文件复制到systemd
cp $FILE /lib/systemd/system/
sudo systemctl daemon-reload
# sudo systemctl enable $FILE

# 如果是 RPI 3，需要重新映射 UART 引脚
set_dtoverlay_pi_three

# 设置 cmdline.txt 和 config.txt 的配置
do_serial

# 确保所有配置的网络设备在继续启动之前都启动并分配了IP地址
sudo systemctl enable systemd-networkd-wait-online.service

# 更新和升级树莓派，否则由于不一致可能导致构建失败
sudo apt-get update -y 

# 获取所需的库
sudo apt-get install -y --force-yes jq dnsutils inadyn usb-modeswitch modemmanager network-manager openvpn network-manager-openvpn \
                                     dh-autoreconf gstreamer1.0-tools gstreamer1.0-plugins-good gstreamer1.0-plugins-bad
#                                 wvdial build-essential cmake libboost-all-dev libconfig++-dev libreadline-dev

# 安装web界面的参数选项
args=$1                           
argsToLower=$(echo "$args" | tr '[:upper:]' '[:lower:]')
case $argsToLower in
          "web")
            echo Installing UAVcast including Web interface # 安装包括Web界面的UAVcast
            # 运行Web安装
            sudo sh $DIR/./web.sh
        ;;
        *)
         printf "\n\n NOTE!!!  Installing UAVcast without Web Interface \n\n\n use web argurment ( ./install.sh web ) to install web UI.\n\n\n\n"
        ;;
esac

################# 编译 UAV 软件 ############
# UAVcast依赖
mkdir $Basefolder/packages
cd $Basefolder/packages

#Mavproxy
git clone https://gitee.com/culapple/cmavnode.git

# 创建cmavnode的符号链接
sudo ln -s $Basefolder/usr/bin/cmavnode /usr/bin/cmavnode

# 完成
printf "\n\n\n安装完成。\n 重启RPI并通过浏览器打开RPI的IP地址访问UAVcast web界面。\n"
